<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <el-icon class="stat-icon bg-blue"><User /></el-icon>
            <div>
              <div class="stat-label">总用户数</div>
              <div class="stat-value">{{ stats.totalUsers }}</div>
              <div class="stat-trend" :class="stats.userTrend >= 0 ? 'positive' : 'negative'">
                <el-icon>
                  <CaretTop v-if="stats.userTrend >= 0" />
                  <CaretBottom v-else />
                </el-icon>
                {{ Math.abs(stats.userTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <el-icon class="stat-icon bg-green"><ShoppingCart /></el-icon>
            <div>
              <div class="stat-label">今日订单</div>
              <div class="stat-value">{{ stats.todayOrders }}</div>
              <div class="stat-trend" :class="stats.orderCompare >= 0 ? 'positive' : 'negative'">
                同比 {{ stats.orderCompare }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <el-icon class="stat-icon bg-orange"><Coin /></el-icon>
            <div>
              <div class="stat-label">销售额</div>
              <div class="stat-value">¥{{ stats.salesAmount }}</div>
              <div class="stat-trend" :class="stats.salesCompare >= 0 ? 'positive' : 'negative'">
                环比 {{ stats.salesCompare }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <el-icon class="stat-icon bg-purple"><Box /></el-icon>
            <div>
              <div class="stat-label">库存总量</div>
              <div class="stat-value">{{ stats.inventory }}</div>
              <div class="stat-trend" :class="stats.inventoryPercent >= 50 ? 'positive' : 'negative'">
                剩余 {{ stats.inventoryPercent }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 核心图表区 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>API响应时间分析</span>
              <el-tag size="small" effect="dark" type="primary">实时数据</el-tag>
            </div>
          </template>
          <div ref="examAccuracyChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>页面停留时间分析</span>
              <el-tag size="small" effect="dark" type="success">用户行为</el-tag>
            </div>
          </template>
          <div ref="stayDurationChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部图表组 -->
    <el-row :gutter="20">
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>API访问排名</span>
              <el-tag size="small" effect="dark" type="info">TOP 10</el-tag>
            </div>
          </template>
          <div ref="userChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>API错误率分析</span>
              <el-tag size="small" effect="dark" type="danger">异常监控</el-tag>
            </div>
          </template>
          <div ref="productChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户行为路径分析</span>
              <el-tag size="small" effect="dark" type="warning">流量分析</el-tag>
            </div>
          </template>
          <div ref="gaugeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { 
  User, ShoppingCart, Coin, Box, CaretTop, CaretBottom 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 图表实例
const examAccuracyChart = ref(null)
const userChart = ref(null)
const productChart = ref(null)
const gaugeChart = ref(null)
const stayDurationChart = ref(null)
let examAccuracyInstance = null
let userInstance = null
let productInstance = null
let gaugeInstance = null
let stayDurationInstance = null

// 数据状态
const stats = reactive({
  totalUsers: 1258,
  userTrend: 12.5,
  todayOrders: 156,
  orderCompare: 8.2,
  salesAmount: 25680,
  salesCompare: -3.8,
  inventory: 1890,
  inventoryPercent: 76
})

// API基础URL
const API_BASE_URL = 'http://localhost:3000'

// 获取API响应时间数据
const fetchApiResponseTimeData = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/analysis/api-access/response-time`)
    if (response.data) {
      initApiResponseTimeChart(response.data)
    }
  } catch (error) {
    console.error('获取API响应时间数据失败:', error)
    ElMessage.error('获取API响应时间数据失败')
  }
}

// 获取API错误率数据
const fetchApiErrorRateData = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/analysis/api-access/error-rate`)
    if (response.data) {
      initApiErrorRateChart(response.data)
    }
  } catch (error) {
    console.error('获取API错误率数据失败:', error)
    ElMessage.error('获取API错误率数据失败')
  }
}

// 获取API访问排名数据
const fetchApiRankingData = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/analysis/api-access/ranking`)
    if (response.data) {
      initApiRankingChart(response.data)
    }
  } catch (error) {
    console.error('获取API访问排名数据失败:', error)
    ElMessage.error('获取API访问排名数据失败')
  }
}

// 获取用户行为路径分析数据
const fetchUserPathData = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/analysis/user-behavior/path-analysis`)
    if (response.data) {
      initUserPathChart(response.data)
    }
  } catch (error) {
    console.error('获取用户行为路径分析数据失败:', error)
    ElMessage.error('获取用户行为路径分析数据失败')
  }
}

// 获取用户停留时间数据
const fetchStayDurationData = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/analysis/user-behavior/stay-duration`)
    if (response.data) {
      initStayDurationChart(response.data)
    }
  } catch (error) {
    console.error('获取用户停留时间数据失败:', error)
    ElMessage.error('获取用户停留时间数据失败')
  }
}

// 初始化API响应时间图表
const initApiResponseTimeChart = (chartData) => {
  if (!examAccuracyInstance) {
    examAccuracyInstance = echarts.init(examAccuracyChart.value)
  }
  
  const option = {
    ...chartData,
    title: {
      text: 'API响应时间与请求量分析',
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 16,
        color: '#666'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '70px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = `<div style="font-weight:bold;margin-bottom:5px;">${params[0].name}</div>`;
        params.forEach(param => {
          const color = param.color;
          const seriesName = param.seriesName;
          const value = param.value;
          const marker = `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>`;
          result += `${marker}${seriesName}: ${value}<br/>`;
        });
        return result;
      }
    },
    series: [
      {
        ...chartData.series[0],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      },
      {
        ...chartData.series[1],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#f5a97f' },
            { offset: 0.5, color: '#f56c6c' },
            { offset: 1, color: '#f56c6c' }
          ])
        }
      },
      {
        ...chartData.series[2],
        lineStyle: {
          color: '#67c23a',
          width: 3,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 10
        },
        itemStyle: {
          color: '#67c23a',
          borderWidth: 2,
          borderColor: '#fff'
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }
  
  examAccuracyInstance.setOption(option)
}

// 初始化API错误率图表
const initApiErrorRateChart = (chartData) => {
  if (!productInstance) {
    productInstance = echarts.init(productChart.value)
  }
  
  const option = {
    ...chartData,
    title: {
      text: 'API错误率分布',
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 16,
        color: '#666'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '50px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}%',
      axisPointer: {
        type: 'shadow'
      }
    },
    series: [{
      ...chartData.series[0],
      itemStyle: {
        color: params => {
          // 根据错误率设置不同的颜色
          const value = params.value;
          if (value >= 80) return '#f56c6c';  // 高错误率：红色
          if (value >= 30) return '#e6a23c';  // 中等错误率：橙色
          if (value >= 10) return '#f0c78a';  // 低错误率：浅橙色
          return '#67c23a';                   // 极低错误率：绿色
        },
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}%',
        fontSize: 12,
        fontWeight: 'bold'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0,0,0,0.3)'
        }
      }
    }]
  }
  
  productInstance.setOption(option)
}

// 初始化API访问排名图表
const initApiRankingChart = (chartData) => {
  if (!userInstance) {
    userInstance = echarts.init(userChart.value)
  }
  
  const option = {
    ...chartData,
    title: {
      text: 'API访问量排名',
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 16,
        color: '#666'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '50px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    series: [{
      ...chartData.series[0],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ]),
        borderRadius: [0, 4, 4, 0]
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#5cbbff' },
            { offset: 0.7, color: '#0e7bef' },
            { offset: 1, color: '#0e7bef' }
          ])
        }
      }
    }]
  }
  
  userInstance.setOption(option)
}

// 初始化用户行为路径分析图表
const initUserPathChart = (chartData) => {
  if (!gaugeInstance) {
    gaugeInstance = echarts.init(gaugeChart.value)
  }
  
  try {
    // 处理数据中可能存在的循环
    const processedData = {
      ...chartData,
      series: [{
        ...chartData.series[0],
        // 过滤掉可能导致循环的链接
        links: chartData.series[0].links.filter((link, index) => {
          // 检查是否存在反向链接
          const hasReverse = chartData.series[0].links.some((otherLink, otherIndex) => {
            return index !== otherIndex && 
                  link.source === otherLink.target && 
                  link.target === otherLink.source
          })
          
          // 如果存在反向链接，只保留值较大的那个
          if (hasReverse) {
            const reverseLink = chartData.series[0].links.find(otherLink => 
              link.source === otherLink.target && link.target === otherLink.source
            )
            return link.value >= (reverseLink?.value || 0)
          }
          
          return true
        })
      }]
    }
    
    // 使用处理后的数据，添加自定义配置
    const option = {
      ...processedData,
      title: {
        text: '用户行为路径流向',
        left: 'center',
        top: 0,
        textStyle: {
          fontSize: 16,
          color: '#666'
        }
      },
      tooltip: {
        ...processedData.tooltip,
        formatter: '{b} → {c}',
        backgroundColor: 'rgba(50,50,50,0.9)',
        borderColor: '#ccc',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        }
      },
      series: [{
        ...processedData.series[0],
        left: '5%',
        right: '5%',
        top: '50px',
        bottom: '5%',
        nodeWidth: 20,
        nodeGap: 8,
        label: {
          position: 'right',
          fontSize: 10,
          color: '#555'
        },
        lineStyle: {
          color: 'source',
          curveness: 0.5
        },
        itemStyle: {
          color: '#1f77b4',
          borderColor: '#fff'
        },
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 2
          }
        }
      }]
    }
    
    gaugeInstance.setOption(option)
  } catch (error) {
    console.error('渲染用户行为路径分析图表失败:', error)
    
    // 如果桑基图渲染失败，显示备用图表
    const fallbackOption = {
      title: {
        text: '热门用户行为路径',
        subtext: '(数据结构复杂，显示TOP 5)',
        left: 'center',
        top: 0,
        textStyle: {
          fontSize: 16,
          color: '#666'
        },
        subtextStyle: {
          fontSize: 12,
          color: '#999'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 50,
        type: 'scroll',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '路径流量',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData.series[0].links
            .sort((a, b) => b.value - a.value)
            .slice(0, 5)
            .map(link => ({
              name: `${link.source} → ${link.target}`,
              value: link.value
            }))
        }
      ]
    }
    
    gaugeInstance.setOption(fallbackOption)
  }
}

// 初始化用户停留时间图表
const initStayDurationChart = (chartData) => {
  if (!stayDurationInstance) {
    stayDurationInstance = echarts.init(stayDurationChart.value)
  }
  
  const option = {
    ...chartData,
    title: {
      text: '页面停留时间分析',
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 16,
        color: '#666'
      }
    },
    legend: {
      data: ['平均停留时间', '访问次数'],
      top: 30,
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      left: '3%',
      right: '5%',
      bottom: '15%',
      top: '70px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    series: [
      {
        ...chartData.series[0],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#5cbbff' },
              { offset: 0.7, color: '#0e7bef' },
              { offset: 1, color: '#0e7bef' }
            ])
          }
        }
      },
      {
        ...chartData.series[1],
        lineStyle: {
          color: '#ff7f50',
          width: 3,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 10
        },
        itemStyle: {
          color: '#ff7f50',
          borderWidth: 2,
          borderColor: '#fff'
        },
        symbol: 'circle',
        symbolSize: 8,
        emphasis: {
          scale: true
        }
      }
    ]
  }
  
  stayDurationInstance.setOption(option)
}

// 添加窗口resize监听
const handleResize = () => {
  examAccuracyInstance?.resize()
  userInstance?.resize()
  productInstance?.resize()
  gaugeInstance?.resize()
  stayDurationInstance?.resize()
}

// 初始化
onMounted(() => {
  // 获取API响应时间数据
  fetchApiResponseTimeData()
  
  // 获取API错误率数据
  fetchApiErrorRateData()
  
  // 获取API访问排名数据
  fetchApiRankingData()
  
  // 获取用户行为路径分析数据
  fetchUserPathData()
  
  // 获取用户停留时间数据
  fetchStayDurationData()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 销毁图表实例
  examAccuracyInstance?.dispose()
  userInstance?.dispose()
  productInstance?.dispose()
  gaugeInstance?.dispose()
  stayDurationInstance?.dispose()
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
/* 基础容器样式 */
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

/* 统计卡片样式 */
.stat-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  }

  .stat-item {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 20px;

    .stat-icon {
      flex-shrink: 0;
      padding: 16px;
      border-radius: 12px;
      font-size: 28px;
      color: white;
      transition: transform 0.3s;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

      /* 图标背景色 */
      &.bg-blue { background: linear-gradient(135deg, #409eff, #007bff); }
      &.bg-green { background: linear-gradient(135deg, #67c23a, #4caf50); }
      &.bg-orange { background: linear-gradient(135deg, #e6a23c, #ff9800); }
      &.bg-purple { background: linear-gradient(135deg, #8a48f3, #6c5ce7); }
    }

    .stat-label {
      color: #909399;
      font-size: 14px;
      line-height: 1.4;
      margin-bottom: 4px;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      margin: 6px 0;
      color: #303133;
    }

    .stat-trend {
      font-size: 13px;
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 2px 8px;
      border-radius: 12px;
      width: fit-content;
      
      &.positive {
        color: #67c23a;
        background-color: rgba(103, 194, 58, 0.1);
      }
      
      &.negative {
        color: #f56c6c;
        background-color: rgba(245, 108, 108, 0.1);
      }
    }
  }
}

/* 图表卡片样式 */
.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  }

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    
    span {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .chart-container {
    height: 320px;
    padding: 10px;
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .stat-card .stat-item {
    padding: 16px;
    
    .stat-icon {
      padding: 14px;
      font-size: 24px;
    }
    
    .stat-value {
      font-size: 24px;
    }
  }
  
  .chart-card .chart-container {
    height: 280px;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 15px;
  }
  
  .stat-card .stat-item {
    padding: 14px;
    gap: 15px;
    
    .stat-icon {
      padding: 12px;
      font-size: 20px;
    }
    
    .stat-value {
      font-size: 20px;
    }
  }
  
  .chart-card {
    .chart-header {
      padding: 12px 16px;
      
      span {
        font-size: 14px;
      }
    }
    
    .chart-container {
      height: 250px;
    }
  }
}

/* 通用间距类 */
.mb-4 { margin-bottom: 24px; }
</style>